package com.lh.jianzhioffer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author: linghao
 * @since: 2023/2/12
 *
 *
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回
 */
public class 从尾到头打印链表06 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(3);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(1);
        node1.next = node2;
        node2.next = node3;
        System.out.println(reversePrint(node1)[2]);
    }


    public static int[] reversePrint(ListNode head) {
        ListNode newNode = reverseNode(head);
        List<Integer> list =  new ArrayList<>();
        while(newNode != null){
            list.add(newNode.val);
            newNode = newNode.next;
        }
        int[] ints = new int[list.size()];
        for(int i=0;i<list.size();i++){
            ints[i] = list.get(i);
        }
        return ints;
    }

    private static ListNode reverseNode(ListNode head) {
        ListNode cur = null;
        while(head != null){
            ListNode temp = head.next;
            head.next = cur;
            cur = head;
            head = temp;
        }
        return cur;
    }

    public static class ListNode {
         int val;
         ListNode next;
         ListNode(int x) { val = x; }
     }
}
